package com.imgrate.migration.service;

import com.imgrate.migration.entity.User;
import com.imgrate.migration.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    public User createUser(String username, String password, String email, String fullName) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setFullName(fullName);
        user.setRole("USER"); // 默认角色为USER
        
        User savedUser = userRepository.save(user);
        log.info("创建新用户: {}", username);
        return savedUser;
    }
    
    public User createUserWithRole(String username, String password, String email, String fullName, String role) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setFullName(fullName);
        user.setRole(role); // 设置角色
        
        User savedUser = userRepository.save(user);
        log.info("创建新用户: {}，角色: {}", username, role);
        return savedUser;
    }
    
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    public boolean validatePassword(String username, String password) {
        log.info("开始验证密码 - 用户名: {}, 密码长度: {}", username, password.length());
        
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            log.info("找到用户 - ID: {}, 用户名: {}, 数据库中的密码哈希: {}", user.getId(), user.getUsername(), user.getPassword());
            
            boolean matches = passwordEncoder.matches(password, user.getPassword());
            log.info("密码匹配结果: {}", matches);
            
            return matches;
        } else {
            log.warn("未找到用户: {}", username);
            return false;
        }
    }
    
    public void updateLastLogin(String username) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setLastLogin(LocalDateTime.now());
            userRepository.save(user);
        }
    }
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public User updateUser(Long id, String email, String fullName) {
        Optional<User> userOpt = userRepository.findById(id);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setEmail(email);
            user.setFullName(fullName);
            return userRepository.save(user);
        }
        throw new RuntimeException("用户不存在");
    }
    
    public User updateUserRole(Long id, String role) {
        Optional<User> userOpt = userRepository.findById(id);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setRole(role);
            return userRepository.save(user);
        }
        throw new RuntimeException("用户不存在");
    }
    
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
        log.info("删除用户ID: {}", id);
    }
    
    public User updateUserPassword(Long id, String newPassword) {
        Optional<User> userOpt = userRepository.findById(id);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setPassword(passwordEncoder.encode(newPassword));
            return userRepository.save(user);
        }
        throw new RuntimeException("用户不存在");
    }
    
    public List<User> getUsersByTimeRange(LocalDateTime start, LocalDateTime end) {
        return userRepository.findByCreatedAtBetween(start, end);
    }
    
    public long getUserCount() {
        return userRepository.count();
    }
    
    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }
    
    public List<User> getOnlineUsers() {
        return userRepository.findByLastLoginAfter(LocalDateTime.now().minusDays(1));
    }
    
    public List<User> getNewUsers() {
        return userRepository.findByCreatedAtBetween(LocalDateTime.now().minusWeeks(1), LocalDateTime.now());
    }
}